package org.brownflat.lighthouse.monitoring.ci.hudson;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.monitoring.ci.ConnectionException;
import org.brownflat.lighthouse.monitoring.ci.Feed;
import org.brownflat.lighthouse.monitoring.ci.HTTPServer;
import org.brownflat.lighthouse.monitoring.ci.Monitorable;

public class HudsonServer extends HTTPServer implements Monitorable {
    private static final Logger LOG = Logger.getLogger(HudsonServer.class);
    private String[] views = {""};
    private BrokenBuildDecisionMaker decisionMaker;

    private boolean lastRunHasBrokenBuilds = false;

    public HudsonServer(String host, int port) {
        super(host, port);
    }

    public HudsonServer(String host, int port, String path) {
        super(host, port, path);
    }

    public void setBrokenBuildDecisionMaker(BrokenBuildDecisionMaker decisionMaker) {
        this.decisionMaker = decisionMaker;
    }

    public void setViews(String[] views) {
        this.views = views;
    }

    @Override
    public void run() {
        boolean broken = false;

        for (String view : views) {
            HudsonLatestBuildsRequest request = new HudsonLatestBuildsRequest(view);
            String response = null;
            try {
                response = execute(request);
            } catch (ConnectionException e) {
                LOG.error("Couldn't communicate with Hudson... indicating the build is broken...", e);
            }

            if (decisionMaker != null) {
                lastRunHasBrokenBuilds = decisionMaker.broken(response);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(String.format("View [%s] query content [%s], broken [%s]", view, response, broken));
                }
            }
        }
    }

    @Override
    public String getName() {
        return "Hudson";
    }

    @Override
    public boolean isBroken() {
        return lastRunHasBrokenBuilds;
    }

    @Override
    public Feed getLatestFeed() {
        return new Feed();
    }

    @Override
    public String getLocation() {
        return getUrl();
    }
}
